import React from 'react'
import { Spin, Row, Col } from 'antd'
import Condition from 'components/condition'
const { If, Else } = Condition;
import dashboardService from "containers/dashboard/dashboard.service";
import {messages} from "share/common";
import { connect } from 'react-redux';
import constants from 'share/constants'
import menuRoute from 'routes/menuRoute'
import formCodeList from 'routes/formcode-csvjson.json'

import NullCard from "containers/dashboard/dashboard-component/null-card"
import CardTitle from "containers/dashboard/dashboard-component/card-title"

import ApprovingEditImg from 'images/dashboard/home-approve-doing.png'
import ApprovingPassImg from 'images/dashboard/home-approve-pass.png'
import ApprovingRejectImg from 'images/dashboard/home-approve-reject.png'
import EditingDrawbackImg from 'images/dashboard/home-drawback.png'

class DynamicDocuments extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      load: false,
      documentActive: []
    }
  }

  componentWillMount() {
    this.getDocumentActive()
  }

  getDocumentActive = () => {
    const { profile } = this.props;
    this.setState({load: true});
    dashboardService.getLatestActive().then(res => {
      let resultData = [];
      res.data.length && res.data.map(item => {
        if (!profile['ca.web.disabled'] || item.entityType !== '1001') {
          resultData.push(item);
        }
      });
      this.setState({
        load: false,
        documentActive: resultData
      })
    })
  };

  goDocumentDetail = (item) => {
    console.log('[DEBUG] goDocumentDetail', item)
    let url;
    // let formType = Number(item.formType);
    // if (formType < 3000) {
    //   if (formType === 2005 ||formType === 2006) {
    //     url = menuRoute.getRouteItem('loan-detail').url.replace(':formOID', item.formOID).replace(':loanBillOID', item.entityOID).replace(':pageFrom', "history");
    //   }
    //   //formType：2001（差旅申请）、2002（费用申请）、2003（订票申请）、2004（京东申请）
    //   //status === 1001 编辑申请单
    //   if((formType === 2001 || formType === 2002 || formType === 2003) && item.status === 1001) {
    //     url = menuRoute.getRouteItem('business-and-gift-application-giftDetail').url.replace(':formOID', item.formOID).replace(':applicationOID', item.entityOID).replace(':id', item.id);
    //   }
    //   // if(formType === 2004 && item.status === 1001) {
    //   //   url = menuRoute.getRouteItem('jd-request-edit').url.replace(':formOID', item.formOID).replace(':applicationOID', item.entityOID);
    //   // }
    //   if((formType === 2001 || formType === 2002 || formType === 2003 || formType === 2004) && item.status !== 1001){
    //     // TODO 先修复废弃的key，之后可能需要修改
    //     const formItem = formCodeList.find(item => item.formCode === formCode)
    //     url = menuRoute.getRouteItem('business-and-gift-application-giftDetail').url.replace(':formOID', item.formOID).replace(':applicationOID', item.entityOID).replace(':id', item.id).replace(':pageFrom','my');
    //   }
    // } else {
    //   url = menuRoute.getRouteItem('expense-report-detail').url.replace(':expenseReportOID', item.entityOID).replace(':pageFrom', 'my');
    // }
    let backUrlKey = undefined
    switch(Number(item.entityType)) {
      case 1001:
          menuRoute.goForm(this, item.formCode, {
            action: 'detail',
            backUrlKey,
            params: {
              formOID: item.formOID,
              applicationOID: item.entityOID,
              pageFrom: 'my',
              id: item.id
            },
            needOpen: true
          })
          break;
      case 1002:
          menuRoute.goForm(this, item.formCode, {
            action: 'detail',
            backUrlKey,
            params: {
              expenseReportOID: item.entityOID,
              pageFrom: 'my',
            },
            needOpen: true
          })
          break;
      case 3001:
        url =`/main/loan-billing/my-borrow/loan-detail/${item.formOID}/${item.entityOID}/:pageFrom/:applicationOID`
        // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`);
        window.open(`${window.ISIE9 ? "#" : ""}${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`, '_blank');
        break;
      case 4001:
        this.approveOtherDetail = menuRoute.getRouteItem('done-approve-other-detail', 'key'); //其他单审批详情页
        url = this.approveOtherDetail.url.replace(':formOID', item.formOID).replace(':entityOID', item.entityOID).replace(':backType', 'history');
        // this.context.router.push(`${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`);
        window.open(`${window.ISIE9 ? "#" : ""}${url}${url.indexOf("?")>-1?'&':"?"}backUrlKey=${backUrlKey}`, '_blank');
        break;
    }
  };

  render() {
    const {load, documentActive} = this.state;
    const {removeModule} = this.props;
    return (
      <Spin spinning={load}>
        <CardTitle  cardKey={"3"}
                    title={messages('dashboard.key26'/*单据动态*/)}
                    removeModule={(key) => removeModule(key)}
                    reloadModule={this.getDocumentActive}/>
        <div className="card-content">
          <Condition>
            <If value={documentActive.length}>
              <div className="active-content">
                {documentActive.map(item => (
                  <div className="latest-item" onClick={() => this.goDocumentDetail(item)} key={item.entityOID}>
                    <Row>
                      <Col span={1}>
                        <div className="state-icon">
                          {item.rejectType === 1000 && (constants.getTextByValue(Number(item.status), 'documentStatus', 'state') === "processing" &&
                            <img src={ApprovingEditImg}/>)}
                          {item.rejectType === 1000 && (constants.getTextByValue(Number(item.status), 'documentStatus', 'state') === "success" &&
                            <img src={ApprovingPassImg}/>)}
                          {item.rejectType !== 1000 && (constants.getTextByValue(Number(item.status + '' + item.rejectType), 'documentStatus', 'state') === "warning" &&
                            <img src={EditingDrawbackImg}/>)}
                          {item.rejectType !== 1000 && (constants.getTextByValue(Number(item.status + '' + item.rejectType), 'documentStatus', 'state') === "error" &&
                            <img src={ApprovingRejectImg}/>)}
                        </div>
                      </Col>
                      <Col span={23}>
                        <div className="base-info">
                          {new Date(item.lastModifiedDate).format('yyyy-MM-dd hh:mm:ss')}
                          <span>{(item.approvalHistorys && item.approvalHistorys[0].operator) ? item.approvalHistorys[0].operator.fullName : ''}</span>
                          {item.approvalHistorys ? item.approvalHistorys[0].operationDescription : ''}
                          <div className="business-code f-right">{item.businessCode}</div>
                        </div>
                        <div className="form-info">
                                  <span>
                                    {item.formName}
                                  </span>
                          {item.formCode === 'SQ024' ?
                            (
                              <sapn className="f-right">检查通过</sapn>
                            ):(<span className="f-right">
                                    <span>{item.currencyCode}</span>{this.filterMoney(item.totalAmount)}
                                  </span>
                            )
                          }
                        </div>
                        {item.title || item.remark
                          ?
                          <div className="document-title">{`${item.title ? item.title : ""}${item.title && item.remark ? "，" : ""}${item.remark ? item.remark : ""}`}</div>
                          :
                          <div className="document-title">-</div>
                        }
                      </Col>
                    </Row>
                  </div>
                ))}
                <div className="dynamic-document-tips">{messages('dashboard.key27'/*最多显示5条（近60天）*/)}</div>
              </div>
            </If>
            <Else>
              <NullCard imgType={"dynamicDoc"} message={messages('dashboard.key160')/*这里将显示近60天的单据动态*/}/>
            </Else>
          </Condition>
        </div>
      </Spin>
    )
  }
}

DynamicDocuments.propTypes = {
  removeModule: React.PropTypes.func.isRequired
};

DynamicDocuments.defaultProps={
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile
  }
}

export default connect(mapStateToProps)(DynamicDocuments)
